<template>
  <div>
    <div
        style="width: 1670px;min-height:770px;padding:24px 32px;margin:15px 0 15px 35px;
        border-radius: 26px;background-color: white">
      <div v-if="contentShow">
        <p style="margin: 0;font-size: 18px">课件</p>
        <el-collapse v-model="activeNames" @change="handleChange" style="margin-top: 20px">
          <el-collapse-item v-for="(item,index) in chapterList" :title="item.chapterName" :name="index">
            <div v-for="(it,ind) in lessonList" v-if="it.chapterId===item.chapterId"
                 style="margin: 20px 0 30px 30px;" :id="'lesson'+index+'-'+ind">
              <div style="display: flex;height: 32px">
              <el-link :href="'/#/learnEdit/contentEdit/'+item.courseId+'/'+item.chapterId+'/'+it.lessonId"
                       style="font-size: 16px;" :underline="false">
                <div style="display: flex;height: 32px;width: 1570px;padding-top: 8px">
                  <a v-if="it.content" class="el-icon-circle-check" style="border-radius: 50%;
                background-color: #409EFF;color: white;font-size: 24px;height: 24px;width: 24px"></a>
                  <a v-else class="el-icon-remove-outline" style="font-size: 24px;"></a>
                  <div style="margin: 4px 0 0 8px;width: 30%">{{ it.lessonName }}</div>
                  <div style="width: 65%">
                </div>
                </div>
              </el-link>
              <el-button type="danger" size="small" style="height: 32px;margin-bottom: 8px" :key="'lesson'+it.lessonId"
                                   icon="el-icon-delete" @click="openDeleteLesson(it.lessonId)" circle></el-button>
            </div></div>
            <div style="height: 60px;white-space:nowrap;">
            <el-button class="el-icon-plus" type="primary" :key="'add-'+item.chapterId" @click="onAddLensson(item.chapterId)"
                       style="margin:10px 0 10px 30px">添加课时
            </el-button>
              <el-button type="danger" :key="'delete-'+item.chapterId" @click="openDeleteChapter(item.chapterId)"
                                   style="float:right;margin:10px 60px 10px 30px">删除章节
            </el-button>
              <el-button type="primary" :key="'update-'+item.chapterId" @click="onUpdateChapter(item.chapterId,item.chapterName)"
                         style="float:right;margin:10px 10px 10px 30px">修改章节
              </el-button>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-button class="el-icon-plus" type="primary" @click="onAddChapter()" style="float: right;margin: 40px">
          添加章节
        </el-button>
        <el-dialog
            :visible.sync="addVisible"
            width="30%"
            top="300px"
            center>
          <el-form v-if="addLessonFlag" :model="addLesson" :rules="rules" ref="lessonFrom"
                   style="width: 70%;margin-left: 75px">
            <p style="text-align: center;width: 100%;font-size: 20px">新增课时</p>
            <el-form-item prop="lessonName">
              <el-input v-model="addLesson.lessonName" placeholder="请输入课时名"
                        style="width: 350px;height: 46px;margin:10px 0">
              </el-input>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button type="primary" style="width: 300px" @click="addLessonRun(courseId,chapterId)">确 定</el-button>
            </el-form-item>
          </el-form>
          <el-form v-else :model="addChapter" :rules="rules" ref="chapterFrom" style="width: 70%;margin-left: 75px">
            <p style="text-align: center;width: 100%;font-size: 20px">新增章节</p>
            <el-form-item prop="chapterName">
              <el-input v-model="addChapter.chapterName" placeholder="请输入章节名"
                        style="width: 350px;height: 46px;margin:10px 0">
              </el-input>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button type="primary" style="width: 300px" @click="addChapterRun(courseId)">确 定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-dialog
            :visible.sync="updateVisible"
            width="30%"
            top="300px"
            center>
          <el-form :model="updateChapter" :rules="rules" ref="updateChapterFrom" style="width: 70%;margin-left: 75px">
            <p style="text-align: center;width: 100%;font-size: 20px">修改章节</p>
            <el-form-item prop="chapterName">
              <el-input v-model="updateChapter.chapterName" placeholder="请输入章节名"
                        style="width: 350px;height: 46px;margin:10px 0">
              </el-input>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button type="primary" style="width: 300px" @click="updateChapterRun(courseId,chapterId)">确 定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div v-if="!contentShow">
        <p style="margin: 0;font-size: 18px">
          <el-form style="display: flex;">
            <a style="margin-top: 6px">课件</a>
            <i class="el-icon-arrow-right" style="margin: 10px"></i>
            <el-form-item style="width: 150px">
              <el-select v-model="chapterId" placeholder="请选择章节">
                <el-option @click.native="onClickChapter" v-for="(item,index) in chapterList"
                           :key="item.chapterId" :label="item.chapterName" :value="item.chapterId"></el-option>
              </el-select>
            </el-form-item>
            <i class="el-icon-arrow-right" style="margin: 10px"></i>
            <el-form-item style="width: 150px">
              <el-select v-model="lessonId" placeholder="请选择课时">
                <el-option @click.native="onClickLesson()" v-for="(item,index) in lessonList"
                           v-if="item.chapterId===chapterId"
                           :key="item.lessonId" :label="item.lessonName" :value="item.lessonId"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </p>
        <el-form :model="lesson" :rules="rules" label-width="30px" style="display: flex;flex-direction: column;width: 1200px;" ref="lessonContentForm">
          <el-form-item prop="content">
            <div id="div1">
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="float: right;width: 150px;height: 60px;font-size: 20px" @click="addOrUpdate('lessonContentForm')">提 交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import E from 'wangeditor'
export default {
  name: "ContentEditView",
  data() {
    return {
      activeNames: ['1'],
      courseId: '',
      chapterList: [],
      lessonList: [],
      contentShow: false,
      chapterId: '',
      lessonId: '',
      lesson: '',
      addLesson: {lessonName:''},
      addChapter: {chapterName:''},
      updateChapter:{chapterName:''},
      addLessonFlag: false,
      addVisible: false,
      updateVisible:false,
      rules: {
        lessonName: {required: true, message: '课时名不能为空', trigger: 'blur'},
        chapterName: {required: true, message: '章节名不能为空', trigger: 'blur'}
      }
    }
  },
  methods: {
    onAddLensson(chapterId) {
      if (this.$refs.lessonFrom!==undefined) {
      this.$nextTick(() => {
        this.$refs.lessonFrom.resetFields();
      });}
      this.addLessonFlag = true;
      this.chapterId = chapterId;
      this.addVisible = true;
    },
    onAddChapter() {
      if (this.$refs.chapterFrom!==undefined) {
      this.$nextTick(() => {
        this.$refs.chapterFrom.resetFields();
      });}
      this.addLessonFlag = false;
      this.addVisible = true;
    },
    onUpdateChapter(chapterId,chapterName){
      this.updateChapter.chapterName=chapterName;
      this.chapterId=chapterId;
      this.updateVisible=true;
    },
    addLessonRun(courseId, chapterId) {
      this.$refs.lessonFrom.validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "http://localhost:8089/user/lesson/createLesson",
            data: {"lessonName": this.addLesson.lessonName, "courseId": courseId, "chapterId": chapterId}
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.msg);
              this.getLessonByCourseId(courseId);
              this.addVisible=false;
            } else
              this.$message.error(res.data.msg)
          }).catch(err => console.log(err));
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addChapterRun(courseId) {
      this.$refs.chapterFrom.validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "http://localhost:8089/user/chapter/createChapter",
            data: {"chapterName": this.addChapter.chapterName, "courseId": courseId}
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.msg);
              this.getChapterByCourseId(courseId);
              this.addVisible=false;
            } else
              this.$message.error(res.data.msg)
          }).catch(err => console.log(err));
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    updateChapterRun(courseId,chapterId){
      this.$refs.updateChapterFrom.validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "http://localhost:8089/user/chapter/updateChapter",
            data: {"chapterName": this.updateChapter.chapterName, "courseId": courseId,"chapterId":chapterId}
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success("修改章节成功");
              this.getChapterByCourseId(courseId);
              this.updateVisible=false;
            } else
              this.$message.error(res.data.msg)
          }).catch(err => console.log(err));
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    updateLesson(){
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/user/lesson/updateLesson",
        data: this.lesson
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.msg);
        } else
          this.$message.error(res.data.msg)
      }).catch(err => console.log(err));
    },
    openDeleteChapter(chapterId) {
      this.$confirm('此操作将永久删除该章节, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteChapter(chapterId);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    openDeleteLesson(lessonId){
      this.$confirm('此操作将永久删除该课时, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteLesson(lessonId);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteChapter(chapterId){
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/user/chapter/deleteChapter/${chapterId}`
      }).then(res => {
        if(res.data.code===200){
          this.$message.success(res.data.msg);
          this.getChapterByCourseId(this.courseId);
        }else
          this.$message.error(res.data.msg)
      }).catch(err => console.log(err));
    },
    deleteLesson(lessonId){
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/user/lesson/deleteLesson/${lessonId}`
      }).then(res => {
        if(res.data.code===200){
          this.$message.success(res.data.msg);
          this.getLessonByCourseId(this.courseId);
        }else
          this.$message.error(res.data.msg)
      }).catch(err => console.log(err));
    },
    getChapterByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/chapter/selectChapterByCourseId/${courseId}`
      }).then(res => {
        if(res.data.code===200)
        this.chapterList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getLessonByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/lesson/selectLessonByCourseId/${courseId}/${localStorage.getItem("userId")}`
      }).then(res => {
        if(res.data.code===200)
        this.lessonList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getLessonById(lessonId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/lesson/selectLesson/${lessonId}`
      }).then(res => {
        if (res.data.code === 200)
          this.lesson = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    //创建富文本编辑器，并进行上传图片、上传视颜的配置
    createRichTextEditor() {
      this.editor = new E('#div1');
      this.editor.config.uploadImgServer = 'http://localhost:8089/richText/uploadFile?type=img';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadVideoServer = 'http://localhost:8089/richText/uploadFile?type=video';
      this.editor.config.uploadVideoName = 'file';
      this.editor.config.placeholder = '请在此处安排课时';
      this.editor.config.height=2000
      this.editor.config.zIndex=500
      this.editor.create();
    },
    //确定按钮
    addOrUpdate(formName) {
      console.log(this.editor.txt.html());
      this.lesson.content = this.editor.txt.html();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateLesson();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleChange(val) {
      console.log(val);
    },
    onClickChapter() {
      this.lessonId = "";
    },
    onClickLesson() {
      this.$router.push({
        path: '/learnEdit/contentEdit/' + this.courseId + '/' + this.chapterId + '/' + this.lessonId
      }).catch(err => console.log(err));
    }
  },
  created() {
    this.courseId = parseInt(this.$route.params.courseId);
    this.chapterId = parseInt(this.$route.params.chapterId);
    this.lessonId = parseInt(this.$route.params.lessonId);
    // this.contentShow=false;
    if (!this.chapterId){
      this.contentShow = true;
    }
    else {
      this.getLessonById(this.lessonId);
      this.$nextTick(() => {
        if (!this.editor) {
          this.createRichTextEditor();
        }
        console.log(this.taskscore);
      });
    }
    this.getChapterByCourseId(this.courseId);
    this.getLessonByCourseId(this.courseId);
  },
  beforeUpdate() {
    if(!this.contentShow) {
      if (this.lesson.content != null)
        this.editor.txt.html(`${this.lesson.content}`);
    }
  }
}
</script>

<style scoped>

/deep/ .el-collapse-item__header {
  color: #333333;
  font-size: 16px;
  margin-top: 15px;
  border-radius: 10px;
  padding: 5px 20px;
  background-color: #F7F7F7 !important;
  position: relative;
}

/deep/ .el-collapse-item__content {
  text-align: left;
//color: #fff ; //background-color: #313743; padding-bottom: 0;

  div {
    height: .96rem;
    line-height: .96rem;
  }
}
</style>